// pages/register/register.js
const app = getApp()
const cfg = require("../../utils/config.js");
const utilMd5 = require('../../utils/MD5.js');
Page({

  /**
   * 页面的初始数据
   */
  data: {
    nvabarData: {
      showCapsule: 1, //是否显示左上角图标  1表示显示  0表示不显示
      title: '注册', //导航栏 中间的标题
      white: true, // 是就显示白的，不是就显示黑的。
      address: '' // 加个背景 不加就是没有
    },
    height: app.globalData.height * 2 + 30,
    checkIcon: '../../images/Check3x.png',
    logIcon: '../../images/logo1-6.png',
    radioValue: [
      {id: 1, name: "企业"},
        {id: 2, name: "个人", checked: "true"}
    ],
    regTel: '',
    regPsd:'',
    regName:'',
    personName:'',
    bankCode: 2,
    isCodeIng:false,//获取验证码状态，倒计时
    codeTxt:'获取验证码', //获取验证码
    loginCode: '',
    codeDisabled: false, // 验证码按钮是否禁用
    regDisabled: false, //提交按钮是否禁用
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    //this.getBankList();
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },
  getPhoneCode:function(){
      console.log('获取验证码')
    var _this = this;
    if (_this.data.regTel == "") {
      wx.showToast({
        title: '请输入手机号',
        icon: 'none',
        duration: 2000
      })
      return false;
    }
    if (!(/^1[345789]\d{9}$/.test(_this.data.regTel))) {
      wx.showToast({
        title: '手机号码填写有误',
        icon: 'none',
        duration: 2000
      })
      return false
    }
      _this.setData({codeDisabled: true,});
      if (!_this.data.isCodeIng) {
      let time = 60;
      let timer = setInterval(function() {
           time--;
           _this.setData({
               codeTxt: '(' + time + 's)后再获取',
              isCodeIng : true
           });
           if (time <= 0) {
                _this.setData({
                  codeTxt : '获取验证码',
                    isCodeIng: false,
                    codeDisabled: false,
               });
                clearInterval(timer);
           }
          //  console.log('time--',time)
       }, 1000);
       _this.getPhoneCodeAjax(_this.data.regTel);
    }
  },
  getPhoneCodeAjax: function(phoneNum) {
      // console.log('phoneNum ------ '+phoneNum)
    wx.request({
      url: cfg.requestURL +'/backend/agent/mobile/getSmsCode',
      data: {"mobile": phoneNum},
      method: 'GET',
      header: {'content-type': 'application/json'},
      success(res) {
        console.log('验证码发送成功！');
      }
    })
  },
  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },
  changePsd: function (e) {
    this.setData({
      regPsd: e.detail.value
    })
  },
  agreement: function () {
    wx.navigateTo({
      url: '../agreement/agreement'
    })
  },
  changeName: function (e) {
    console.log(e.detail.value)
    this.setData({
      regName: e.detail.value
    })
  },
  changeTel: function (e) {
    console.log(e)
    this.setData({
      regTel: e.detail.value
    })
  },
  changePersonName:function(e){
    console.log(e)
    this.setData({
      personName: e.detail.value
    })
  },
  // 注册
  addBank: function () {
    var _this = this;
    if (_this.data.regName.trim() == "" && _this.data.bankCode == 1) {
      wx.showToast({
        title: '请输入公司名称',
        icon: 'none',
        duration: 2000
      })
      return false;
    }
    if (_this.data.regTel.trim() == "") {
      wx.showToast({
        title: '请输入手机号',
        icon: 'none',
        duration: 2000
      })
      return false;
    }
    if (!(/^1[3456789]\d{9}$/.test(_this.data.regTel))) {
      wx.showToast({
        title: '手机号码填写有误',
        icon: 'none',
        duration: 2000
      })
      return false
    }
    if (_this.data.loginCode.trim() == "") {
      wx.showToast({
        title: '请填入验证码',
        icon: 'none',
        duration: 2000
      })
      return false;
    }
    if (_this.data.regPsd.trim() == "") {
      wx.showToast({
        title: '请输入密码',
        icon: 'none',
        duration: 2000
      })
      return false;
    }
    var url = '';      
    var data = {};
      if (_this.data.bankCode == 1) {  //商户注册
      url = cfg.requestURL + '/backend/seller/mobile/register';
      data = {
        "companyName": _this.data.regName,
        "loginName": _this.data.regTel,
        "password": utilMd5.hexMD5(_this.data.regPsd),
        "verifyCode": _this.data.loginCode
      }
      } else { //个人注册
      url = cfg.requestURL + '/backend/person/mobile/register';
      data = {
        "companyName":  _this.data.regTel,//_this.data.personName,
        "loginName":  _this.data.regTel,//_this.data.personName,
        "password": utilMd5.hexMD5(_this.data.regPsd),
        "verifyCode": _this.data.loginCode
      }
    }
      //防重复提交
      if (_this.data.regDisabled) {
          return false;
      }
      wx.showLoading({
          title: '注册中...',
      })
      //提交信息注册
    wx.request({
      url: url, //仅为示例，并非真实的接口地址
      data: data,
      method: 'POST',
      header: {
        'content-type': 'application/json' // 默认值
      },
      success(res) {
          _this.setData({regDisabled: true,});
        if (res.data.flag) {
          var msg = JSON.parse(res.data.msg);
          wx.setStorageSync("agentId", msg.data.agentId);
          wx.setStorageSync("token", msg.data.token);
          wx.setStorageSync("userId", msg.data.userId);
          wx.setStorageSync("authorityName", msg.data.authorityName);
          wx.setStorageSync("loginName", msg.data.loginName);

          // 未登录用户注册跳转到之前页面
          var _exprs = wx.getStorageSync("noLoginInfoSv") || [];
          if (_exprs.length > 1) {
            wx.navigateTo({
              url: '/' + _exprs[0],
            })
          } else {
            wx.navigateTo({
              url: '../index/index'
            })
          }        
        } else {
          wx.showToast({
            title: res.data.msg,
            icon: 'none',
            mask: true,
            duration: 1500
          })
        }
      }
    });

      setTimeout(function () {
          wx.hideLoading();
          // console.log('可以继续注册')
          _this.setData({regDisabled: false,});
      }, 3000);
  },
  // 选择企业或个人时，页面输入内容变动
  selectRegisterType: function(e) {
    var id = e.detail.value;
      // console.log(id)
    this.setData({
      bankCode: id,
      regTel : ''
    })
  },
  changeBank: function (event) {
    let postId = event.currentTarget.dataset.id;
    let name = event.currentTarget.dataset.name;
    this.setData({
      bankCode: postId
    })
    this.hideModal();
  }
})